import java.util.Arrays;
import java.util.HashMap;

public class Leetcode {
    public static void main(String[] args) {
        int[] arr={2, 7, 11, 15};
        Leetcode l=new Leetcode();
        System.out.println(Arrays.toString(l.twoSum2(arr,18)));
    }
    public int[] twoSum(int[] nums, int target) {
        int[] a=new int[2];
        for(int i=0;i<nums.length-1;i++){
            for(int j=i+1;j<nums.length;j++){
                if(nums[i]+nums[j]==target){
                    a[0]=i;
                    a[1]=j;
                    return a;
                }
            }
        }
        return null;
    }
    public int[] twoSum2(int[] nums, int target){
        int[] a=new int[2];
        HashMap<Integer,Integer> h=new HashMap<>();
        for(int i=0;i<nums.length;i++){
            if(h.containsKey(nums[i])){
                a[0]=i;//2
                a[1]=h.get(nums[i]);//1
                return a;
            }
            //key为补数
            h.put(target-nums[i],i);//{16:0,11:1,}
        }
        return a;
    }
}
